package cn.itsuorce.service.impl;

import cn.itsuorce.domain.Employee;
import cn.itsuorce.domain.Shop;
import cn.itsuorce.domain.dto.ShopDto;
import cn.itsuorce.mapper.EmployeeMapper;
import cn.itsuorce.mapper.ShopMapper;
import cn.itsuorce.query.ShopQuery;
import cn.itsuorce.service.IShopService;
import cn.itsuorce.utils.AjaxResult;
import cn.itsuorce.utils.MailUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop,ShopQuery> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private MailUtils mailUtils;
    @Override
    public AjaxResult settledIn(ShopDto shopDto) {
        //先保存员工信息，返回主键
        Employee admin = new Employee();
        //copy对象的属性：要求两个对象的属性名称一致，才能copy
        BeanUtils.copyProperties(shopDto, admin);
        employeeMapper.save(admin);

        //再保存店铺信息
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopDto, shop);
        shop.setAdmin_id(admin.getId());
        shopMapper.save(shop);
        return AjaxResult.me();
    }

    /**
     * 入驻审核
     * @param shop
     */
    @Override
    @Transactional
    public void audit(Shop shop) {
        //1. 直接通过shop_id修改店铺的state
        shopMapper.updateStateById(shop.getId(), shop.getAuditState());

        //2. 通过id修改店铺关联的员工state
        employeeMapper.updateStateById(shop.getAdmin().getId(), shop.getAuditState());

        //3. 发送激活邮件【推荐使用子线程去发送邮件】
        String text = "<h2 style='color:red;'>欢迎你入驻到宠物之家平台，点击以下链接进行激活：</h2><br/><br/>" +
                "<a href='http://localhost:8080/shop/activation/"+shop.getId()+"/"+shop.getAdmin().getId()+"'>立即激活</a>";
        mailUtils.sendMail(shop.getAdmin().getEmail(), "商家入驻激活", text);
    }

    /**
     * 邮件激活
     * @param shop_id
     * @param employee_id
     */
    @Override
    public void activation(Long shop_id, Long employee_id) {
        shopMapper.activation(shop_id);
        employeeMapper.activation(employee_id);
    }
}
